package com.chenglu.android.search;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenglu.android.R;
import com.chenglu.android.common.base.BaseActionBarActivity;
import com.chenglu.android.common.net.Constant;
import com.chenglu.android.common.utils.BaseDialog;
import com.chenglu.android.common.utils.KeyboardUtils;
import com.chenglu.android.common.utils.SPUtils;
import com.chenglu.android.common.utils.ToastUtils;
import com.chenglu.android.search.adapter.SearchHistoryAdapter;
import com.chenglu.android.search.bean.KeyWordsHositoryBean;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author: lyj
 * @Created: by Copyright 2023/10/22 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * @Description：搜索历史中间页
 */
public class SearchHistoryActivity extends BaseActionBarActivity {

    public static final String SHOPSTYPEID = "shopsId";
    @BindView(R.id.et_search_goods)
    EditText etSearchGoods;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.iv_search_delete)
    ImageView ivSearchDelete;
    @BindView(R.id.rv_search_history)
    RecyclerView rvSearchHistory;
    @BindView(R.id.ll_seaech_hisrory)
    LinearLayout llSeaechHisrory;

    private SearchHistoryAdapter historyAdapter;

    String mHositoryText;

    private Gson mGson;
    private List<KeyWordsHositoryBean> mList;

    private String shopId;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_history_goods;
    }

    @Override
    protected void initView() {

        setCenterText("搜索");
        shopId =  getIntent().getStringExtra(SHOPSTYPEID);
        initEditSearch();
    }

    @Override
    protected void onResume() {
        super.onResume();

        mHositoryText = SPUtils.getString(Constant.KEYWORDS_HOSITORY, "");

        if (TextUtils.isEmpty(mHositoryText)) {
            llSeaechHisrory.setVisibility(View.GONE);
        } else {
            llSeaechHisrory.setVisibility(View.VISIBLE);
            initflowRv();
            mGson = new Gson();

            mList = mGson.fromJson(mHositoryText, new TypeToken<List<KeyWordsHositoryBean>>() {
            }.getType());
            if (mList != null && !mList.isEmpty()) {
                //  设置搜索历史本地数据；
                historyAdapter.setNewData(mList);
            }


        }
    }

    //初始化数据
    private void initflowRv() {

        //2，增加谷歌流式布局
        FlexboxLayoutManager manager = new FlexboxLayoutManager(mContext, FlexDirection.ROW, FlexWrap.WRAP) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        rvSearchHistory.setLayoutManager(manager);
        historyAdapter = new SearchHistoryAdapter(mContext, mList);

        rvSearchHistory.setAdapter(historyAdapter);
//        historyAdapter.notifyDataSetChanged();
        historyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {


                Intent intent = new Intent(mContext, SearchResultActivity.class);
                intent.putExtra(SearchResultActivity.SEARCHNAME, historyAdapter.getData().get(position).getKeyWords());
                intent.putExtra(SearchResultActivity.SHOPSTYPEID, shopId);
                startActivity(intent);
                //跳转搜索结果页
                KeyboardUtils.hideKeyboard(etSearchGoods);

            }
        });
    }


    /**
     * @description 搜索名字和方法
     */

//    private String searchname;

    private void initEditSearch() {

        etSearchGoods.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                //点击时的线
                if (hasFocus) {
//                    mLine.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
                    String txt = etSearchGoods.getText().toString();
//                    searchname = txt;
                    if (notBlank(txt)) {//                        点击触碰时的线
                        ivClear.setVisibility(View.VISIBLE);

                    } else {
                        ivClear.setVisibility(View.GONE);

                    }
                }
            }
        });

        //搜索确定键
        etSearchGoods.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    searchHistoryName();

                }
                return false;
            }
        });

        etSearchGoods.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() < 1) {
                    ivClear.setVisibility(View.GONE);

                } else {
                    ivClear.setVisibility(View.VISIBLE);

                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        ivClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSearchGoods.setText("");
            }
        });


    }

    private void searchHistoryName() {

        String keyWords = etSearchGoods.getText().toString().trim();
        if (TextUtils.isEmpty(keyWords)) {
            ToastUtils.show("请输入搜索关键词");
            return;
        }
        if (mList == null) {
            mList = new ArrayList<>();
        }
        KeyWordsHositoryBean keyWordsHositoryBean = new KeyWordsHositoryBean();
        keyWordsHositoryBean.setKeyWords(keyWords);
        if (!mList.contains(keyWordsHositoryBean)) {
            mList.add(0, keyWordsHositoryBean);

            if (mList.size() > 10) {
                for (int i = 10; i < mList.size(); i++) {
                    mList.remove(i);
                }
            }
//            Log.e("size",mList.size()+"size");
            String str = new Gson().toJson(mList);
            SPUtils.setString(Constant.KEYWORDS_HOSITORY, str);
        }
//        SPUtils.setString(Constant.SEARCHNAME,keyWords);
        KeyboardUtils.hideKeyboard(etSearchGoods);
        Intent intent = new Intent(mContext, SearchResultActivity.class);
        intent.putExtra(SearchResultActivity.SEARCHNAME, keyWords);
        intent.putExtra(SearchResultActivity.SHOPSTYPEID, shopId);
        startActivity(intent);
    }

    public static boolean notBlank(String str) {
        return str != null && !"".equals(str.trim());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @OnClick({R.id.ll_search, R.id.iv_search_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_search:
                searchHistoryName();
                break;
            case R.id.iv_search_delete:
                BaseDialog.showDialog(mContext, "清空历史搜索", "取消", "确定", new OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        SPUtils.remove(Constant.KEYWORDS_HOSITORY);
                        mList.clear();
                        llSeaechHisrory.setVisibility(View.GONE);

                    }
                },false);

                break;
        }
    }
}
